package ubi.quando.UI;

import ubi.quando.c2dm.C2DMBaseReceiver;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class C2DMReceiver extends C2DMBaseReceiver {

	private UbiApplication mApp;

	public C2DMReceiver() {
		// Email address currently not used by the C2DM Messaging framework
		super("ubiquando.huji@gmail.com");
	}

	@Override
	public void onRegistered(Context context, String registrationId)
			throws java.io.IOException {
		// The registrationId should be send to your applicatioin server.
		// We just log it to the LogCat view
		// We will copy it from there
		if (mApp == null) {
			mApp = (UbiApplication) getApplication();
		}
		mApp.getServerComm().registerServer(registrationId, mApp.getMail(),
				mApp.getPwd());

		Log.e("C2DM", "Registration ID arrived: Fantastic!!!");
		Log.e("C2DM", registrationId);
	};

	@Override
	protected void onMessage(Context context, Intent intent) {
		if (mApp == null) {
			mApp = (UbiApplication) getApplication();
		}
		
		Log.e("C2DM", "Message: Fantastic!!!");
		// Extract the payload from the message
		Bundle extras = intent.getExtras();
		if (extras != null) {
			String notification = (String) extras.get("payload");
			String[] typeAndId = notification.split("#");
			if (typeAndId.length == 1) {
				typeAndId = notification.split(":");
				String type = typeAndId[0];
				String id = typeAndId[1];
				if (type.equals("eventStart")) {
					mApp.HandleEventStarted(id);
				} else if (type.equals("contactAdded")) {
					mApp.HandleContactAdded(id);
				} else if (type.equals("offerPickup")) {
					mApp.HandleOfferPickup(id);
				} else if (type.equals("pickupConfirmed")){
					mApp.HandlePickupConfirmed(id);
				}
			}
			else if(typeAndId.length == 2)
			{
				String[] first = typeAndId[0].split(":");
				String[] sec = typeAndId[1].split(":");
				if(first[0].equals("eventInvite"))
				{
					// Meeting invitation
					mApp.HandleEventInvite(first[1], Integer.parseInt(sec[1]), null, null, Long.MIN_VALUE);
				}
				if (first[0].equals("eventUpdate"))
				{
					mApp.HandleUpdateEvent(first[1], Integer.parseInt(sec[1]));
				}			
				else if(first[0].equals("clientLoc"))
				{
					mApp.HandleUpdateLocation(first[1], sec[1]);
				} else if (first[0].equals("friendRequest")) {
					mApp.HandleFriendRequest(first[1], sec[1]);
				}
			}
			else if(typeAndId.length == 5)
			{
				String[] first = typeAndId[0].split(":");
				String[] sec = typeAndId[1].split(":");
				String[] thrd = typeAndId[2].split(":");
				String[] fourth = typeAndId[3].split(":");
				String[] fifth = typeAndId[4].split(":");
				
				// PickUp invitation
				if(first[0].equals("eventInvite"))
				{
					mApp.HandleEventInvite(first[1], Integer.parseInt(sec[1]), thrd[1], fourth[1], Long.parseLong(fifth[1]));
				}
			}
		}
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.e("C2DM", "Error occured!!!");
	}

}